package bank_access;

import mware_lib.Config;
import mware_lib.NameServiceMessage;
import mware_lib.Stub;

public class AccountStub extends AccountImplBase {
    private NameServiceMessage msg;
    private String splitString = Config.splitString;

    public AccountStub(NameServiceMessage msg) {
        this.msg = msg;
    }

    @Override
    public void transfer(double amount) throws OverdraftException {
        if(Config.DEBUGGER) System.out.println("Transfer mit Menge: " + amount + " und MSG :" + msg.toString());
        Stub stub = new Stub();
        stub.setReference(msg);
        stub.setMethod("transfer");
        stub.addParameter(double.class, amount);
        String receive = stub.send();
        String[] splits = receive.split(splitString);
        if (splits[0].equals("ERROR")) {
            if(Config.DEBUGGER) System.out.println("Transfer ERROR " + splits[1]);
            //if (splits[1].contains("OverdraftException")) {
                if(Config.DEBUGGER) System.out.println("Account OverdraftException : " + splits[2] );
                throw new OverdraftException(splits[2]);
            //}
        }
    }

    @Override
    public double getBalance() {
        if(Config.DEBUGGER) System.out.println("Balance mit MSG :" + msg.toString());
        Stub stub = new Stub();
        stub.setReference(msg);
        stub.setMethod("getBalance");
        String receive = stub.send();
        String[] splits = receive.split(splitString);
        if (splits[0].equals("ERROR")) {
            if(Config.DEBUGGER) System.out.println("getBalance ERROR");
            if(Config.DEBUGGER) System.out.println("Account RuntimeException : " + splits[2] );
            throw new RuntimeException(splits[2]);
        }

        return Double.parseDouble(receive);
    }
}
